/**
 * 
 */
package com.gr.staffpm.user.model;

import org.apache.wicket.model.LoadableDetachableModel;

import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.security.service.UserService;


/**
 * @author Graham Rhodes 31 Dec 2010 12:28:17
 */
public class DetachableUserModel extends LoadableDetachableModel<User> {

    private final long id;
    private final UserService userService;
    private static final long serialVersionUID = 1L;

    public DetachableUserModel(UserService userService, User u) {
        this(userService, Long.valueOf(u.getUserId()));
    }

    public DetachableUserModel(UserService userService, long id) {
        this.userService = userService;
        if (id == 0) {
            throw new IllegalArgumentException();
        }
        this.id = id;
    }

    @Override
    public int hashCode() {
        return Long.valueOf(id).hashCode();
    }

    /**
     * Used for dataview with ReuseIfModelsEqualStrategy item reuse strategy
     * 
     * @see org.apache.wicket.markup.repeater.ReuseIfModelsEqualStrategy
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (obj instanceof DetachableUserModel) {
            DetachableUserModel other = (DetachableUserModel) obj;
            return other.id == id;
        }
        return false;
    }


    @Override
    protected User load() {
        // loads project from the database
        return userService.getUser((int) id);
    }

}
